'''
自定义存储系统
1设置客户端
2上传图片给storage
3保存file_idv
'''
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client

from mall import settings

@deconstructible
class MyStorage(Storage):
    def __init__(self, conf_path=None,ip=None):
        if not conf_path:
            conf_path = settings.FDFS_CLIENT_CONF
        self.conf_path=conf_path
        if not ip:
            ip=settings.FDFS_URL
        self.ip=ip
    def _save(self,name,content,max_length=None):
        # self, name, content, max_length=None
        # 创建客户端
        client=Fdfs_client(self.conf_path)

        # 获取图片
        data=content.read()
#         上传
        result=client.upload_by_buffer(data)
        if result.get('Status') =='Upload successed.' :
            file_id=result.get('Remote file_id')
        else:
            raise  Exception('上传失败')
        return file_id

    def _open(self, name, mode='rb'):
        pass
    def exists(self,name):
        return False
    # exist存在返回true,不存在返回false,我们的目标是不存在的上传上去,raise false
    def url(self,name):
        # return 'http://192.168.139.128:8888/'+name
        return self.ip+name


client=Fdfs_client('utils/fastdfs/client.conf')
client.upload_by_filename('/home/python/Desktop/123.jpg')
'''
{'Remote file_id': 'group1/M00/00/00/wKiLgFx5LlqAAcspAADy2h4qn9w271.jpg',
 'Status': 'Upload successed.', 'Group name': 'group1',
 'Uploaded size': '60.00KB', 'Storage IP': '192.168.139.128',
 'Local file name': '/home/python/Desktop/123.jpg'}
'''


